package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrdersTask {
    @Autowired
    private OrderMapper ordersMapper;

      /*
        每分钟触发一次，查询待支付订单超时情况
     */
    @Scheduled(cron = "0 * * * * ?")
    public void ordersTask() {
        log.info("定时处理超时订单:{}", LocalDateTime.now());
        //调用mapper查询一些待支付且时间超过15分钟后的订单
        LocalDateTime now = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList = ordersMapper.GetByOrders(Orders.PENDING_PAYMENT,now);
        if(ordersList!=null&&ordersList.size()>0){
            for(Orders orders:ordersList){
                //更改订单状态
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时，自动取消");
                orders.setCancelTime(LocalDateTime.now());
                ordersMapper.update(orders);
            }
        }
    }
//    /*
//        每天凌晨1点进行触发
//     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void cancelOrdersTask() {
        log.info("定时处理位于派送中的订单:{}", LocalDateTime.now());
       //查询昨天派送中的订单
        LocalDateTime now = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = ordersMapper.GetByOrders(Orders.DELIVERY_IN_PROGRESS,now);
        if(ordersList!=null&&ordersList.size()>0){
            for(Orders orders:ordersList){
                //更改订单状态
                orders.setStatus(Orders.COMPLETED);
                ordersMapper.update(orders);
            }
        }
    }
}
